#!/usr/local/bin/python
'''
Created on 2012/05/05

@author: Ryu Naeki
'''

import urllib2
import json
import datetime
import re
import cgi
import cgitb
cgitb.enable()

from DaoTweet import DaoTweet

class ImportTweet(object):
    '''
    classdocs
    '''

    def __init__(self):
        '''
        Constructor
        '''
        
    def run(self):
        SEARCH_REQUEST = "http://search.twitter.com/search.json?include_entities=true&q=%23hackearthquakes"

        f = urllib2.urlopen(SEARCH_REQUEST)
        body = f.read()

        data = json.loads(body)
        # print(json.dumps(data, sort_keys=True, indent=4))

        dao = DaoTweet(DaoTweet.USERNAME, DaoTweet.PASSWORD, DaoTweet.DBNAME, DaoTweet.CHARSET)
        
        results = data["results"]
        for result in results:
            if result["geo"] == None:
                continue
            
            tweet_id = int(result["id"])
            tweet_create_time = datetime.datetime.strptime(result["created_at"], "%a, %d %b %Y %H:%M:%S +0000")
            tweet_user = result["from_user_name"]
            tweet_text = result["text"]
            tweet_geo = result["geo"]["coordinates"]
            tweet_latitude = int(tweet_geo[0])
            tweet_longitude = int(tweet_geo[1])
            tweet_urls = result["entities"]["urls"]
            tweet_expanded_url = tweet_urls[0]["expanded_url"]
            m = re.search("^http:\/\/twitpic.com\/(.+)$", tweet_expanded_url)
            tweet_image_id = m.group(1)
            try:
                dao.add_tweet(tweet_id, tweet_create_time, tweet_user, tweet_text, tweet_latitude, tweet_longitude, tweet_expanded_url, tweet_image_id)
            except:
                pass

if __name__ == "__main__":  
    it = ImportTweet()
    it.run()
    
    print "Content-Type: application/json; charset=utf-8"
    print # blank
    print json.dumps({"result":"OK"}) 

    